//
//  SyntSearchTableview.m
//  diaoyuren
//
//  Created by 钓鱼人 on 16/4/29.
//  Copyright © 2016年 game. All rights reserved.
//

#import "SyntSearchTableview.h"
#import "SyntSearchModel.h"
#import "SynSearchSectionFoot.h"
#import "SelectionCell.h"
#import "NewsCell.h"
#import "thread_listModel.h"
#import "NEWAticListModel.h"
#import "IsLanTabCell.h"
#import "Diaochang_listModel.h"
#import "SeleCtContrl.h"
#import "LoginController.h"
#import "OtherInformationCtrl.h"

@interface SyntSearchTableview ()<UITableViewDataSource,UITableViewDelegate,SelectionCellDeleget>

@property (nonatomic,strong) SyntSearchModel *model;

@property (nonatomic,strong) NSMutableArray *dataAry;
@property (nonatomic,strong) NSUserDefaults *myud;

@property (nonatomic,strong) NSMutableArray  *selecrDataAry;

@property (nonatomic, strong) NSCache * SectionFootCache;

@property (nonatomic, strong) NSCache * cellCache;

@property (nonatomic, strong) NSMutableDictionary * cellHightDic;
@end

@implementation SyntSearchTableview

-(NSMutableDictionary *)cellHightDic{

    if (!_cellHightDic) {
        _cellHightDic = [NSMutableDictionary dictionary];
    }
    return _cellHightDic;
}
-(NSCache *)SectionFootCache{
    if (!_SectionFootCache) {
        _SectionFootCache = [NSCache new];
    }
    return _SectionFootCache;
}
-(NSCache *)cellCache{
    if (!_cellCache) {
        _cellCache = [NSCache new];
    }
    return _cellCache;
}

-(NSMutableArray *)selecrDataAry{

    if (!_selecrDataAry) {
        _selecrDataAry = [NSMutableArray array];
    }
    return _selecrDataAry;
}

-(NSMutableArray *)dataAry{
    if (!_dataAry) {
        _dataAry = [NSMutableArray array];
    }
    return _dataAry;
}

-(instancetype)initWithFrame:(CGRect)frame style:(UITableViewStyle)style{

    if ([super initWithFrame:frame style:style]) {
        
         self.myud = [NSUserDefaults standardUserDefaults];
        
        self.delegate = self;
        self.dataSource =self;
        self.separatorStyle = 0;
        
        [self registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
        
         [self registerNib:[UINib nibWithNibName:@"SelectionCell" bundle:nil] forCellReuseIdentifier:@"Threadcell"];
        
        [self registerClass:[NewsCell class] forCellReuseIdentifier:@"Articlecell"];
        
         [self registerNib:[UINib nibWithNibName:@"IsLanTabCell" bundle:nil] forCellReuseIdentifier:@"dianpucell"];
        
        
        __weak typeof(self) weakSelf = self;
        self.TapBlok = ^{
           
            [weakSelf setSearchString:weakSelf.searchString];
        };
    }
    return self;
}

-(void)setSearchString:(NSString *)searchString{

    _searchString = searchString;
    
    [self.selecrDataAry removeAllObjects];
    [[Manager sharedManager]RequestWhithURL:GetFormhash AndParameter:nil AndCompletionType:^(id responseObject, DIEError *error) {
        if ([responseObject[@"status"] isEqualToString:@"SUCCESS"]) {
        
        [self SearchWhithFormhash:responseObject[@"data"][@"formhash"] AndString:_searchString];
            
        }else{
           
            self.isShowFile = YES;
            [self reloadData];
        
        }
    }];
}

-(void)SearchWhithFormhash:(NSString *)formhash AndString:(NSString *)string{
    
    NSDictionary *dic = @{
                          @"srchtxt":string,
                          @"formhash":formhash,
                          @"search_type":@"all",
                          @"latitude":[self.myud valueForKey:@"latitude"],
                          @"longitude":[self.myud valueForKey:@"longitude"],
                          @"city":[self.myud valueForKey:@"cityPinY"],
                          };
    
    [[Manager sharedManager]ResponseWhithURL:selectSearch AndParameter:dic AndCompletionType:^(id responseObject, DIEError *error) {
        
        if (!error) {
            if ([responseObject[@"status"] isEqualToString:@"SUCCESS"]) {
                self.dataAry = [responseObject[@"data"][@"search_data"] copy];
                
                for (NSDictionary *modelDic in self.dataAry) {
                    
                    if ([modelDic[@"type"] isEqualToString:@"thread"]) {
                        
                        for (NSDictionary *dic in modelDic[@"list"]) {
                            [self.selecrDataAry addObject:[[thread_listModel alloc]initWithDictionary:dic error:nil]];
                        }
                    }
                    
                }
                self.isShowImage = YES;
                [self reloadData];

            }else{
                self.isShowImage = YES;
                [self reloadData];
            }
        }else{
            NSLog(@"网络储蓄哦");
            self.isShowFile = YES;
            [self reloadData];
        }
    }];
    
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    SyntSearchModel *model = [[SyntSearchModel alloc]initWithDictionary:self.dataAry[section] error:nil];
    MBLabelWithFontAdapter *label = [[MBLabelWithFontAdapter alloc]init];
    label.font = [UIFont systemFontOfSize:SCREEN_WIDTH*0.04];
    label.textColor = [UIColor lightGrayColor];
    label.backgroundColor = tabPlainBackColor;
    label.frame = CGRectMake(0, 0, SCREEN_WIDTH,  SCREEN_HEIGHT*0.06);
    label.text = [NSString stringWithFormat:@"    %@",model.title];
    return label;
}


-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    
     NSString *key = [NSString stringWithFormat:@"%ld",(long)section];
    
SyntSearchModel *model = [[SyntSearchModel alloc]initWithDictionary:self.dataAry[section] error:nil];
    
    SynSearchSectionFoot *view = [self.SectionFootCache objectForKey:key];
    
    if (!view) {
        view  = [[NSBundle mainBundle]loadNibNamed:@"SynSearchSectionFoot" owner:nil options:nil].lastObject;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(footTap:)];
        [view addGestureRecognizer:tap];
        
        [_SectionFootCache setObject:view forKey:key];
    }
    view.titleLab.text = model.count;
    if ([model.type isEqualToString:@"thread"]) {
        
            view.tag = 3;

        }else if ([model.type isEqualToString:@"article"]){

            view.tag = 1;

        }if ([model.type isEqualToString:@"video"]){
            view.tag = 2;

        } if ([model.type isEqualToString:@"dianpu"]){
            view.tag = 5;

        }if ([model.type isEqualToString:@"diaochang"]) {
            view.tag = 4;
    }

  view.tableView = tableView;
    view.section = section;
    
    return view;
}

-(void)footTap:(UITapGestureRecognizer *)tap{

    if ([self.mainDelget respondsToSelector:@selector(FootTapClickWhithIndex:)]) {
        [self.mainDelget FootTapClickWhithIndex:tap.view.tag];
    }

}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return SCREEN_HEIGHT*0.07;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{

    return SCREEN_HEIGHT*0.05;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.dataAry.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    SyntSearchModel *model = [[SyntSearchModel alloc]initWithDictionary:self.dataAry[section] error:nil];
    return model.list.count;
}
-(CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 10;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//    UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
    return [[self.cellHightDic valueForKey:[NSString stringWithFormat:@"%ld-%ld",(long)indexPath.section, (long)indexPath.row]]floatValue];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
 SyntSearchModel *model = [[SyntSearchModel alloc]initWithDictionary:self.dataAry[indexPath.section] error:nil];

     NSString *key = [NSString stringWithFormat:@"%ld-%ld",(long)indexPath.section, (long)indexPath.row];
    
    if ([model.type isEqualToString:@"thread"]) {
        SelectionCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Threadcell"];//[self.cellCache objectForKey:key];
        
//        if (!cell) {
//           cell = [tableView dequeueReusableCellWithIdentifier:@"Threadcell"];
            cell.deleget  = self;
//            [self.cellCache setObject:cell forKey:key];
//        }
        cell.model = self.selecrDataAry[indexPath.row];
        [self.cellHightDic setValue:[NSString stringWithFormat:@"%f",cell.height] forKey:key];
        return cell;
        
    }else if ([model.type isEqualToString:@"article"]||[model.type isEqualToString:@"video"]){
    
        NewsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Articlecell"];//[self.cellCache objectForKey:key];
//        if (!cell) {
//            cell =  [tableView dequeueReusableCellWithIdentifier:@"Articlecell"];
//             [self.cellCache setObject:cell forKey:key];
        [self.cellHightDic setValue:[NSString stringWithFormat:@"%f",cell.height] forKey:key];
//        }
       
        cell.model = [[NEWAticListModel alloc]initWithDictionary:model.list[indexPath.row] error:nil];
                return cell;
    
    } if ([model.type isEqualToString:@"dianpu"]||[model.type isEqualToString:@"diaochang"]) {
        
        IsLanTabCell *cell = [tableView dequeueReusableCellWithIdentifier:@"dianpucell"];//[self.cellCache objectForKey:key];
//        if (!cell) {
//            cell = [tableView dequeueReusableCellWithIdentifier:@"dianpucell"];
//            [self.cellCache setObject:cell forKey:key];
        [self.cellHightDic setValue:[NSString stringWithFormat:@"%f",cell.height] forKey:key];
//        }
        
        cell.model = [[Diaochang_listModel alloc]initWithDictionary:model.list[indexPath.row] error:nil];

        return cell;
    }
    else{
//
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];//[self.cellCache objectForKey:key];
//        if (!cell) {
//            cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
//           [self.cellCache setObject:cell forKey:key];
        [self.cellHightDic setValue:[NSString stringWithFormat:@"%f",cell.height] forKey:key];
//        }
        cell.textLabel.text = [NSString stringWithFormat:@"%ld",(long)indexPath.row];
        
        
        return cell;
    }
    
}


#pragma mark--SelectionCell中的代理方法
-(void)CommentSelect:(NSString *)tid Row:(NSInteger)row{
    NSString *url = [NSString stringWithFormat:MainSelet,tid];
    
    SeleCtContrl *str = [SeleCtContrl new];
    str.tid = tid;
    str.url = url;
    str.isSlide = YES;
    str.rowOfCell = row;
    [self.fatherCtrl.navigationController pushViewController:str animated:YES];
}

-(void)UserSpaceClick:(NSString *)uid{
    OtherInformationCtrl *space = [OtherInformationCtrl new];
    space.uid = uid;
    [self.fatherCtrl.navigationController pushViewController:space animated:YES];
}

-(void)PramisNoLogin{
    LoginController *login = [LoginController new];
    [self.fatherCtrl.navigationController pushViewController:login animated:YES];
}

#pragma mark--tableview点击事件
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    SyntSearchModel *model = [[SyntSearchModel alloc]initWithDictionary:self.dataAry[indexPath.section] error:nil];
    
    if ([model.type isEqualToString:@"thread"]) {
        
        SelectionCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        NSString *url = [NSString stringWithFormat:MainSelet,cell.tid];
        
        SeleCtContrl *str = [SeleCtContrl new];
        str.tid = cell.tid;
        str.url = url;
        str.isSlide = NO;
        str.rowOfCell = indexPath.row;
        
        [self.fatherCtrl.navigationController pushViewController:str animated:YES];
        
    }else if ([model.type isEqualToString:@"article"]||[model.type isEqualToString:@"video"]){
        
        NewsCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        if ([self.mainDelget respondsToSelector:@selector(ArticleClickWhithId:AndSkin:)]) {
            [self.mainDelget ArticleClickWhithId:cell.AticleID AndSkin:cell.skin.integerValue];
        }

    } if ([model.type isEqualToString:@"dianpu"]||[model.type isEqualToString:@"diaochang"]) {
        
        IsLanTabCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        
        if ([self.mainDelget respondsToSelector:@selector(IsLanTabClickWhithDetail:AndLatitude:AndLongitude:AndLocaltion:AndID:AndisYujudian:)]) {
            
            [self.mainDelget IsLanTabClickWhithDetail:cell.detail AndLatitude:cell.latitude AndLongitude:cell.longitude AndLocaltion:cell.location AndID:cell.Id AndisYujudian:[model.type isEqualToString:@"dianpu"]];
        }
    }
}

-(void)dealloc{
    
    [self.cellCache removeAllObjects];
    [self.SectionFootCache removeAllObjects];
  
}
@end